package com.hzzy.utils;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

import org.apache.log4j.Logger;

/**
 * 解析 basicParams.properties 里参数值
 * @author 何剑波
 * 2016年5月11日
 */
public class AnalysisBasicParams {
	private static Logger LOGGER = Logger.getLogger(AnalysisBasicParams.class);
	
	private static Properties BASIC_PARAMS = new Properties();
	
	static {
		try {
			BASIC_PARAMS.load(new FileInputStream(AnalysisBasicParams.class.getClassLoader().getResource("basicParams.properties").getFile()));
		} catch (FileNotFoundException e) {
			LOGGER.error(e);
		} catch (IOException e) {
			LOGGER.error(e);
		}
	}
	
	public static String getValueByKey(String key){
		return BASIC_PARAMS.getProperty(key);
	}
	
	/**
	 * 当没有key值得时候，返回默认值
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static String getValueByKey(String key, String defaultValue) {
		return BASIC_PARAMS.getProperty(key, defaultValue);
	}
	
	/**
	 * 写入 properties文件
	 * @param key
	 * @param value
	 * @param comment 注释
	 * @return
	 */
	public static boolean setWriteValueByKey(String key, String value, String comment) {
		BASIC_PARAMS.setProperty(key, value);
		try {
			FileOutputStream fos = new FileOutputStream(AnalysisBasicParams.class.getClassLoader().getResource("system_setting.properties").getFile());
			try {
				BASIC_PARAMS.store(fos, comment != null ? comment : "");
			} catch (IOException e) {
				throw new IOException();
			} finally {
				fos.close();
			}
		} catch (IOException e) {
			LOGGER.error("写入值错误：" + e);
			return false;
		}
		return true;
	}
}
